<?php

namespace App\Console\Commands;

use App\Models\RechargeOrder;
use App\Repositories\Eloquent\AssetCountEloquent;
use App\Services\RechargeOrderService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class RechargeOrderSettleTimer extends Command
{
    protected $assetRepository;
    protected $orderService;
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'rechargeOrder:settle';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Recharge Orders settle timer';

    /**
     * Create a new command instance.
     *
     * @param \App\Repositories\Eloquent\AssetCountEloquent $assetCountEloquent
     * @param \App\Services\RechargeOrderService            $orderService
     */
    public function __construct(AssetCountEloquent $assetCountEloquent, RechargeOrderService $orderService)
    {
        parent::__construct();
        $this->assetRepository = $assetCountEloquent;
        $this->orderService = $orderService;
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //
        $orders = RechargeOrder::where('order_status', 1)
            ->where('is_settle', 0)
            ->today('settled_at')
            ->get();
        if ( ! $orders->isEmpty()) {
            foreach ($orders as $order) {
                try {
                    DB::beginTransaction();
                    $this->assetRepository->operateAsset($order->uid, 'rechargeThaw', $order->order_settle);
                    if ($order->proxy)
                        $this->assetRepository->operateAsset($order->proxy, 'rechargeThaw', $this->orderService->getProxySettle($order));
                    if ($order->business)
                        $this->assetRepository->operateAsset($order->business, 'rechargeThaw', $this->orderService->getBusinessSettle($order));
                    $order->is_settle = 1;
                    $order->save();
                    DB::commit();
                } catch (\Exception $exception) {
                    DB::rollback();
                }
            }
        }

    }
}
